package com.isky.visual.db.factory;

import com.isky.visual.constant.DbConstant;
import com.isky.visual.db.entity.Source;
import com.isky.visual.exception.GlobalException;
import com.isky.visual.result.CodeMsg;
import com.isky.visual.util.DBUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Connection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author wenjs
 */
public class PrestoManager implements IDbManager {
    private Logger log = LoggerFactory.getLogger(PrestoManager.class);

    public static final String  SHOW_COLUMN_SQL = "DESCRIBE %s.%s";
    public static final String  SHOW_TABLE_SQL = "show tables";

    private Source source;

    public PrestoManager(Source source) {
        this.source = source;
    }

    @Override
    public Connection getConnection() {
        Connection connection = null;
        try {
            source.setDbType(DbConstant.Hive);
            connection = DBUtil.getConnection(source);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("数据库获取连接异常" + e.getMessage());
            throw new GlobalException(CodeMsg.DB_CONNECTION_ERROR);
        }
        return connection;
    }

    @Override
    public String getShowColumnSql(String tableName,Source source) {
        String dbName = source.getDbName();
        String[] split = dbName.split("/");
        String schemas = split[split.length-1];
        return String.format(PrestoManager.SHOW_COLUMN_SQL,schemas,tableName);
    }

    @Override
    public String getShowTableSql() {
        String sql = "show tables";
        return sql;
    }

    @Override
    public String getShowTableSql(Source source) {
        String sql = "show tables";
        return sql;
    }

    /**
     * 获取表字段
     * @param con
     * @param sql
     * @return
     */
    @Override
    public List<Map<String, Object>> getTableColumn(Connection con, String sql) throws Exception {
        List<Map<String, Object>> query = DBUtil.query(con, sql);
        List<Map<String, Object>> result = new ArrayList<>();
        if(query != null && !query.isEmpty()){
            for (Map<String, Object> p : query) {
                Map<String, Object> q = new HashMap<>();
                q.put("COLUMN_NAME",p.get("Column")) ;
                q.put("namecn",p.get("Column")) ;
                result.add(q);
            }
        }

        return result;
    }

    @Override
    public String getSingleTableCountSql(String tableName) {
        return "select count(*) as COUNT  from " + this.source.getDbName() + "."+ tableName;
    }

    @Override
    public String getSingleTableDataSql(String tableName, Integer limit) {
        return "select *  from " + this.source.getDbName() + "."+ tableName + " limit " + limit;
    }

}
